package com.guigu.qingcheng.systemservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.qingcheng.pojo.system.TbResource;
import com.guigu.qingcheng.pojo.system.TbRoleResource;
import com.guigu.qingcheng.systemservice.mapper.TbRoleResourceMapper;
import com.guigu.qingcheng.systemservice.service.TbResourceService;
import com.guigu.qingcheng.systemservice.service.TbRoleResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-08
 */
@Service
public class TbRoleResourceServiceImpl extends ServiceImpl<TbRoleResourceMapper, TbRoleResource> implements TbRoleResourceService {

    @Autowired
    private TbRoleResourceService service;

    @Autowired
    private TbResourceService rservice;

    @Override
    public List<Map> getRoleResource(Integer id) {
        QueryWrapper<TbRoleResource> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", id);
        List<TbRoleResource> list = service.list(wrapper);
        List<Map> mapList = new ArrayList<>();
        for( TbRoleResource r: list ){
            TbResource re = rservice.getById(r.getResourceId());
                Map map = new HashMap();
                map.put("id",re.getId());
                map.put("label", re.getResName());
                mapList.add(map);
        }
        return mapList;
    }

    @Transactional
    @Override
    public Boolean toResource(Map<String, Object> qxMap) {
        Boolean f = service.removeById((Serializable) qxMap.get("roleId"));
        ArrayList arrayList = (ArrayList) qxMap.get("resourceId");
        int a = 0;
        for(int i = 0; i < arrayList.size(); i++){
            TbRoleResource r = new TbRoleResource();
            r.setRoleId((Integer) qxMap.get("roleId"));
            r.setResourceId((Integer) arrayList.get(i));
           Boolean f2 = service.save(r);
           if(f2){
               a++;
           }
        }
        if(a == arrayList.size() && f == true){
            return true;
        }
        return false;
    }
}
